package com.ohos.fresco.demo.photo;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TableLayoutManager;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextTool;
import ohos.agp.window.service.Window;
import ohos.bundle.IBundleManager;
import ohos.data.resultset.ResultSet;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import com.facebook.fresco.helper.photoview.PhotoX;
import com.facebook.fresco.helper.photoview.entity.PhotoInfo;
import com.ohos.fresco.demo.ResourceTable;
import com.oszc.bbhmlibrary.utils.LogUtil;

import java.io.File;
import java.util.ArrayList;

/**
 * 显示加载本地相册
 */
public class PhotoAlbumAbility extends Ability {
    private static final int PERMISSION_REQUEST_INTERACTIVE = 1;
    private final static String mPermmReadMedia = "ohos.permission.READ_MEDIA";

    private final String[] IMAGE_PROJECTION = {
        AVStorage.Images.Media.DATA,
        AVStorage.Images.Media.DISPLAY_NAME,
        AVStorage.Images.Media.DATE_ADDED,
        AVStorage.Images.Media.ID,
        AVStorage.Images.Media.MIME_TYPE};

    private ArrayList<PhotoInfo> mImageList = new ArrayList<>();
    private PixelMapWallAdapter mPixelMapWallAdapter;
    private ListContainer mRecyclerView;

    private boolean mIsFinishSearchImage = false; // 是否扫描完了所有图片
    private boolean mIsScanning = false; // 正在扫描
    private DataAbilityHelper mHelper;
    private static final int MINUS_INDEX = -1;
    private int mCursorPosition = MINUS_INDEX; // 当前在数据库查找位置
    private static final int CURSOR_COUNT = 200; // TODO 源库一次加载所有图片，此处限制360为防止溢出

    private EventHandler mHandler;
    /**
     * WHAT_REFRESH_PATH_LIST
     */
    public static final int WHAT_REFRESH_PATH_LIST = 1;

    @Override
    public void onStart(Intent intent) {
        Window window = getWindow();
        window.setStatusBarColor(Color.getIntColor("#313A99"));
        window.setStatusBarVisibility(Component.VISIBLE);
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_local_photo_wall);
        mRecyclerView = (ListContainer) findComponentById(ResourceTable.Id_rv_photo_wall);
        TableLayoutManager manager = new TableLayoutManager();
        manager.setColumnCount(4);
        mRecyclerView.setLayoutManager(manager);
//        mRecyclerView.setScrolledListener(new ScrollListener());
        mHelper = DataAbilityHelper.creator(getContext());
        EventRunner eventRunner = EventRunner.current();
        if (eventRunner == null) {
            return;
        }
        mHandler = new ScanImgHandler(eventRunner);
        checkPermission();
    }
    private void checkPermission() {
        if (verifySelfPermission(mPermmReadMedia) != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission(mPermmReadMedia)) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(
                    new String[]{mPermmReadMedia}, PERMISSION_REQUEST_INTERACTIVE);
            }else {
                Intent intent = new Intent();
                intent.setAction(IntentConstants.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addFlags(Intent.FLAG_ABILITY_NEW_MISSION);
                intent.setUri(Uri.getUriFromParts("package", getBundleName(), null));
                startAbility(intent);
            }
        } else {
            scanImageData();
        }
    }
    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_INTERACTIVE) {
            if (!(grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED)) {
                checkPermission();
            }else {
                scanImageData();
            }
        }
    }
    /**
     * scanImageData
     */
    public void scanImageData() {
        if (mIsFinishSearchImage || mIsScanning) {
            return;
        }
        mIsScanning = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
//                    ------------------
                    ResultSet result = mHelper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null);
                    result.goToRow(mCursorPosition); // 从上一次的扫描位置继续扫描
                    int index = 0;
                    while (result.goToNextRow() && index < CURSOR_COUNT) {
                        index++;
                        int mediaId = result.getInt(result.getColumnIndexForName(IMAGE_PROJECTION[3]));
                        String path = result.getString(result.getColumnIndexForName(IMAGE_PROJECTION[0]));
                        if (!TextTool.isNullOrEmpty(path)) {
                            File mFile = new File(path);
                            if (mFile.exists() && mFile.isFile()) {
                                String name = result.getString(result.getColumnIndexForName(IMAGE_PROJECTION[1]));
                                if (TextTool.isNullOrEmpty(name)) {
                                    continue;
                                }

                                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI,
                                    "" + mediaId);
                                PhotoInfo image = new PhotoInfo();
                                image.setOriginalUrl(path);
                                image.setThumbnailUrl(path);
                                image.setUri(uri.toString());
                                mImageList.add(image);
                            }
                        }
                    }
                    mCursorPosition += index;
                    mIsScanning = false;
                    if (index < CURSOR_COUNT) { // 扫描完了所有图片
                        mIsFinishSearchImage = true;
                    }
                    result.close();
                    mHandler.sendEvent(WHAT_REFRESH_PATH_LIST);
                } catch (DataAbilityRemoteException e) {
                    e.getCause();
                }
            }
        }).start();
    }

    /**
     * 滑动监听
     *
     * @since 2021-04-29
     */
    private class ScrollListener implements ListContainer.ScrolledListener {
        final static int pageItemCount = 10;

        @Override
        public void onContentScrolled(Component component, int i, int i1, int i2, int i3) {
            final int childCount = ((ListContainer) component).getChildCount();
            if (childCount > 0) {
                Component lastChild = ((ListContainer) component).getComponentAt(childCount - 1);
                int lastVisible = ((ListContainer) component).getIndexForComponent(lastChild);
                if (lastVisible + pageItemCount >= mImageList.size() && !mIsFinishSearchImage && !mIsScanning) {
                    scanImageData();
                }
            }
        }
    }

    class ScanImgHandler extends EventHandler {
        ScanImgHandler(EventRunner runner) throws IllegalArgumentException {
            super(runner);
        }

        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }
            switch (event.eventId) {
                case WHAT_REFRESH_PATH_LIST:
                    if (mPixelMapWallAdapter == null) {
                        mPixelMapWallAdapter = new PixelMapWallAdapter(PhotoAlbumAbility.this, mImageList, new OnItemClickListener<PhotoInfo>() {

                            @Override
                            public void onItemClick(Component view, ArrayList<PhotoInfo> photos, int position) {
                                if (photos.size() > 100) {
                                    PhotoX.with(PhotoAlbumAbility.this)
                                        .setPhotoInfo(photos.get(position))
                                        .setCurrentPosition(position)
                                        .start();
                                } else {
                                    PhotoX.with(PhotoAlbumAbility.this)
                                        .setPhotoList(photos)
                                        .setCurrentPosition(position)
                                        .start();
                                }
                            }
                        });
                        mRecyclerView.setItemProvider(mPixelMapWallAdapter);
                    }
//                    else {
//                        mPixelMapWallAdapter.refreshPathList(mImageList);
//                    }
                    break;
                default:
                    break;
            }
        }

        /**
         * distributeEvent
         *
         * @param event
         */
        @Override
        public void distributeEvent(InnerEvent event) {
            super.distributeEvent(event);
        }

    }
}
